package com.ytjj.qmyx.mall.controller.app;

import com.ytjj.common.api.CommonResult;
import com.ytjj.common.controller.BaseController;
import com.ytjj.common.model.UsersResponse;
import com.ytjj.qmyx.mall.enums.UserBalanceSourceEnums;
import com.ytjj.qmyx.mall.model.PlatformStrictDynamicIncomeList;
import com.ytjj.qmyx.mall.model.response.PlatformStrictDynamicIncomeListItemResponse;
import com.ytjj.qmyx.mall.model.response.PlatformStrictDynamicIncomeListResponse;
import com.ytjj.qmyx.mall.model.response.PlatformStrictInfoResponse;
import com.ytjj.qmyx.mall.model.response.PlatformStrictProfitResponse;
import com.ytjj.qmyx.mall.service.DynamicService;
import com.ytjj.qmyx.mall.service.PlatformStrictDynamicIncomeListService;
import com.ytjj.qmyx.mall.service.PlatformStrictInfoService;
import com.ytjj.qmyx.mall.utils.DateUtils;
import com.ytjj.qmyx.users.mapper.UsersBalanceRecordMapper;
import com.ytjj.qmyx.users.mapper.UsersInfoMapper;
import com.ytjj.qmyx.users.mapper.UsersMapper;
import com.ytjj.qmyx.users.model.Users;
import com.ytjj.qmyx.users.model.UsersBalanceRecordStatistics;
import com.ytjj.qmyx.users.model.UsersInfo;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * 达人
 */
@RestController
@RequestMapping("/talent")
@Slf4j
public class AppPlatformStrictInfoController extends BaseController {
    @Autowired
    private PlatformStrictInfoService platformStrictInfoService;
    @Autowired
    private PlatformStrictDynamicIncomeListService platformStrictDynamicIncomeListService;
    @Resource
    private UsersBalanceRecordMapper usersBalanceRecordMapper;
    @Resource
    private UsersMapper usersMapper;
    @Resource
    private UsersInfoMapper usersInfoMapper;
    @Autowired
    private DynamicService dynamicService;

    /**
     * 推荐达人
     *
     * @return
     */
    @GetMapping("/recomment")
    public CommonResult recommentTalent(@RequestParam(required = false, defaultValue = "10") Integer pageSize) {
        List<PlatformStrictInfoResponse> result = platformStrictInfoService.recommentTalent(pageSize);
        return CommonResult.success(result);
    }

    /**
     * 我的收益
     *
     * @param type 1-按天获取  2-按周获取  3-历史量
     * @return
     */
    @GetMapping("/income")
    public CommonResult income(@RequestParam(required = false, defaultValue = "1") Integer type) {
        UsersResponse usersResponse = this.getCurrentUser();
        PlatformStrictProfitResponse response = platformStrictInfoService.incomeInfo(usersResponse.getId(), type);
        return CommonResult.success(response);
    }

    /**
     * 严选官主页-获取严选官榜单排名
     *
     * @return
     */
    @GetMapping("/getListRanking")
    public CommonResult getListRanking(@RequestParam(required = false) Integer id) {
        return CommonResult.success(platformStrictInfoService.getListRanking(id));
    }

    /**
     * 引导下单补贴数据
     */
    @GetMapping("/guidePlaceAnOrder")
    public CommonResult guidePlaceAnOrder() {
        return CommonResult.success(platformStrictInfoService.guidePlaceAnOrder());
    }

    /**
     * 随机展示5个优质测评
     */
    @GetMapping("/getFiveSuperiorDynamic")
    public CommonResult getFiveSuperiorDynamic(){
        return platformStrictInfoService.getFiveSuperiorDynamic();
    }

    /**
     * 达人收益排行榜-昨日榜单
     * @return
     */
    @SneakyThrows
    @GetMapping("/dynamicIncomeRankYesterDay")
    public CommonResult dynamicIncomeRankYesterDay() {
        UsersResponse usersResponse = null;
        try {
            usersResponse = getCurrentUser();
        } catch (Exception e) {
            log.info("=====用户未登陆=====");
            e.printStackTrace();
        }

        List<PlatformStrictDynamicIncomeList> rankList = platformStrictDynamicIncomeListService.selectYesterDayRankList();//昨日假用户榜单
        if (!CollectionUtils.isEmpty(rankList)) {
            /**
             * 如果测评数为0，则按规则赋值
             * 1-10：3-13
             * 11-50：2-8
             * 51-100：1-5
             */
            rankList = rankList.stream().sorted(Comparator.comparing(PlatformStrictDynamicIncomeList::getIncomeAmount)).collect(Collectors.toList());
            AtomicInteger sort = new AtomicInteger(0);
            Random random = new Random();
            rankList.stream().forEach(item -> {
                if (null == item.getDynamicNum() || item.getDynamicNum().equals(0)) {
                    if (sort.get() <= 10) {
                        item.setDynamicNum( 3 + random.nextInt(10));
                    }else if (sort.get() <= 50 && sort.get() >= 11) {
                        item.setDynamicNum(2 + random.nextInt(6));
                    }else if (sort.get() <= 100 && sort.get() >= 51) {
                        item.setDynamicNum(1 + random.nextInt(4));
                    }
                    sort.addAndGet(1);
                }
            });
        }
        Map<String, Object> curDay = DateUtils.getYesterdayTime();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//注意月份是MM
        String startTimeStr = (String) curDay.get("startDate");
        Date startTime = simpleDateFormat.parse(startTimeStr);
        String endTimeStr = (String) curDay.get("endDate");
        Date endTime = simpleDateFormat.parse(endTimeStr);

        PlatformStrictDynamicIncomeListResponse response = method(rankList, startTime, endTime, usersResponse);
        return CommonResult.success(response);
    }

    private PlatformStrictDynamicIncomeListResponse method(List<PlatformStrictDynamicIncomeList> rankList, Date startTime, Date endTime, UsersResponse usersResponse) {
        //获取榜单数据
        List<UsersBalanceRecordStatistics> list = usersBalanceRecordMapper.weekTask(startTime, endTime, UserBalanceSourceEnums.EVALUATION_COMMISSION.name());//所有(真实)用户榜单
        if (!CollectionUtils.isEmpty(list)) {
            list.stream().forEach(item -> {
                Users users = usersMapper.selectByPrimaryKey(item.getUserId());
                UsersInfo usersInfo = usersInfoMapper.selectByPrimaryKey(item.getUserId());
                PlatformStrictDynamicIncomeList obj = new PlatformStrictDynamicIncomeList();
                obj.setUserId(item.getUserId());
                obj.setIncomeAmount(item.getIncomeAmount());
                obj.setNickName(users.getNickname());
                obj.setHeadImg(usersInfo.getHeadImg());
                obj.setDynamicNum(dynamicService.getDynamicCountByUserId(item.getUserId()));
                rankList.add(obj);
            });
        }
        List<PlatformStrictDynamicIncomeListItemResponse> result = new ArrayList<>();
        rankList.stream().forEach(item -> {
            PlatformStrictDynamicIncomeListItemResponse response = new PlatformStrictDynamicIncomeListItemResponse();
            BeanUtils.copyProperties(item, response);
            result.add(response);
        });
        PlatformStrictDynamicIncomeListResponse response = new PlatformStrictDynamicIncomeListResponse();

        List<PlatformStrictDynamicIncomeListItemResponse> mySelfInfo = new ArrayList<>();
        if (null != usersResponse) {
            //获取用户自己数据
            mySelfInfo = result.stream().filter(s -> s.getUserId().equals(usersResponse.getId())).collect(Collectors.toList());//判断自己数据是否在榜单中
            UsersBalanceRecordStatistics myIncomeAmountInfo = usersBalanceRecordMapper.myIncomeAmount(usersResponse.getId(), startTime, endTime, UserBalanceSourceEnums.EVALUATION_COMMISSION.name());
            if (CollectionUtils.isEmpty(mySelfInfo)) {//如果不在榜单中，则表示没有上榜
                response.setHeadImg(usersResponse.getHeadImg());
                response.setIncomeAmount(null == myIncomeAmountInfo ? new BigDecimal(0) : myIncomeAmountInfo.getIncomeAmount());
                response.setMyRank(null);
                response.setNickName(usersResponse.getNickname());
            }else {
                PlatformStrictDynamicIncomeListItemResponse platformStrictDynamicIncomeListItemResponse = mySelfInfo.get(0);
                List<Integer> num = get_num(result, platformStrictDynamicIncomeListItemResponse);
                for (int i = 0; i < result.size(); i++) {
                    if (usersResponse.getId().equals(result.get(i))) {
                        response.setMyRank(i + 1);
                    }
                    response.setHeadImg(usersResponse.getHeadImg());
                    response.setIncomeAmount(null == myIncomeAmountInfo ? new BigDecimal(0) : myIncomeAmountInfo.getIncomeAmount());
                    response.setNickName(usersResponse.getNickname());
                }
            }
            response.setDynamicNum(dynamicService.getDynamicCountByUserId(usersResponse.getId()));
        }
        List<PlatformStrictDynamicIncomeListItemResponse> sortResult = result;
        sortResult = sortResult.stream().sorted(Comparator.comparing(PlatformStrictDynamicIncomeListItemResponse::getIncomeAmount).reversed()).collect(Collectors.toList());
        response.setItem(sortResult);
        if (null != usersResponse && !CollectionUtils.isEmpty(mySelfInfo)) {
            PlatformStrictDynamicIncomeListItemResponse platformStrictDynamicIncomeListItemResponse = mySelfInfo.get(0);
            List<Integer> num = get_num(sortResult, platformStrictDynamicIncomeListItemResponse);
            if (!CollectionUtils.isEmpty(num)){
                response.setMyRank(num.get(0));
            }
        }
        return response;
    }

    /**
     * 达人收益排行榜-今日榜单
     * @return
     */
    @GetMapping("/dynamicIncomeRank")
    public CommonResult dynamicIncomeRank() {
        UsersResponse usersResponse = null;
        try {
            usersResponse = getCurrentUser();
        } catch (Exception e) {
            log.info("=====用户未登陆=====");
            e.printStackTrace();
        }

        List<PlatformStrictDynamicIncomeList> rankList = platformStrictDynamicIncomeListService.selectRankList();//今日假用户榜单if (!CollectionUtils.isEmpty(rankList)) {
        rankList = rankList.stream().sorted(Comparator.comparing(PlatformStrictDynamicIncomeList::getIncomeAmount)).collect(Collectors.toList());
        AtomicInteger sort = new AtomicInteger(0);
        Random random = new Random();
        rankList.stream().forEach(item -> {
            /**
             * 如果测评数为0，则按规则赋值
             * 1-10：3-13
             * 11-50：2-8
             * 51-100：1-5
             */
            if (null == item.getDynamicNum() || item.getDynamicNum().equals(0)) {
                if (sort.get() <= 10) {
                    item.setDynamicNum( 3 + random.nextInt(10));
                }else if (sort.get() <= 50 && sort.get() >= 11) {
                    item.setDynamicNum(2 + random.nextInt(6));
                }else if (sort.get() <= 100 && sort.get() >= 51) {
                    item.setDynamicNum(1 + random.nextInt(4));
                }
                sort.addAndGet(1);
            }
        });
        Map<String, Object> curDay = DateUtils.curDay();
        Date startTime = (Date) curDay.get("dayStart");
        Date endTime = (Date) curDay.get("dayEnd");

        PlatformStrictDynamicIncomeListResponse response = method(rankList, startTime, endTime, usersResponse);
        return CommonResult.success(response);
    }

    /**
     * 寻找该对象在集合中的排名
     * @param list
     * @param a
     * @return
     */
    public static List<Integer> get_num(List<PlatformStrictDynamicIncomeListItemResponse> list, PlatformStrictDynamicIncomeListItemResponse a) {
        List<Integer> list1=new ArrayList<>();
        for(int i=0;i<list.size();i++) {
            if(list.get(i).getUserId().equals(a.getUserId())) {
                list1.add(i);
            }
        }
        return list1;
    }
}
